#include "DHT11.h"
//#include "delay.h"
#define NUMBER 20
#define SIZE 5

extern  uchar Send_Data[20];

extern uchar FlagZd;
extern uchar FlagBc;

uchar flagyw;
uchar flagdoor;
uchar flagrt;

static uchar date[5];
uchar tempstr[]="21";
uchar humistr[]="21";

void DHT11_Init(void)
{
  GPIO_InitType GPIO_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2PERIPH_GPIOB, ENABLE);
  GPIO_StructInit(&GPIO_InitStructure);
  GPIO_InitStructure.GPIO_Pins  =PIN_DHT11;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT_PP;
  GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
  GPIO_Init(PORT_DHT11, &GPIO_InitStructure);
  GPIO_SetBits(PORT_DHT11, PIN_DHT11);
}

static void DHT11_Delay_10us(void)
{
	Delay_1us(10);
}

static BitState DHT11_DATA_IN(void)
{
	if(GPIO_ReadInputDataBit(PORT_DHT11, PIN_DHT11))
		return Bit_SET;
	else
		return Bit_RESET;
}

uchar ReadValue_DHT11(uchar * temp,uchar * humi)
{
  uchar i=0,j,count=0;
  	DHT11_OUT_LOW;
	Delay_1ms(25);
	DHT11_OUT_HIGH;
	DHT11_Delay_10us();
	DHT11_Delay_10us();
	DHT11_Delay_10us();
	DHT11_Delay_10us();
	if(DHT11_DATA_IN()!=0)
	{
	 return ERROR;
	}
  else
	{
		count=0;
	while(DHT11_DATA_IN()==0 && count++<NUMBER);
	  if(count>=NUMBER) return ERROR;
		
		 DHT11_OUT_HIGH;
		
		 while(DHT11_DATA_IN()!=0 && count++<NUMBER)
		if(count>=NUMBER)
			{
				
		return ERROR;
				
			}
			
		for(i=0;i<5;i++)
			{
			  for(j=0;j<8;j++)
				{
				  count=0;
					date[i]=date[i]<<1;
					while(DHT11_DATA_IN()==0 && count++<NUMBER);
						if(count>=NUMBER)
						{
		         return ERROR;
						}
						DHT11_Delay_10us();
						DHT11_Delay_10us();
						DHT11_Delay_10us();
						if(DHT11_DATA_IN()!=0 )
							{
								date[i]=date[i]|0x01;
								count=0;
							while(DHT11_DATA_IN()!=0 && count++<NUMBER );
								if(count>=NUMBER)
								{
								
									return ERROR;
								}
				
					     }
			
		  	}
		
	      }
		if(date[4]!=(date[0]+date[1]+date[2]+date[3]))
			return ERROR;
		else
	     	{
		 * humi = date[0];
		 * temp = date[2];
			return OK;
		    }
 }
}

void Temp_HumiToStr(uchar tempdat,uchar humidat)
{
	 tempstr[0]='0'+tempdat/10;
	 tempstr[1]='0'+tempdat%10;
	 humistr[0]='0'+humidat/10;
	 humistr[1]='0'+humidat%10;
	
	 Send_Data[3]=tempstr[1];
	 Send_Data[2]=tempstr[0];
	 Send_Data[7]=humistr[1];
	 Send_Data[6]=humistr[0];
	 if(FlagZd==0)
	 {
		 Send_Data[10]='0';
	 }
	 else Send_Data[10]='1';
	 if(FlagBc==0)
	 {
		Send_Data[13]='0';
	 }
	 else Send_Data[13]='1';
	 
	 if(flagrt || flagdoor)
	 {
		 Send_Data[16]='1';
	 }
	 else
		 Send_Data[16]='0';
	 
	 if(flagyw)
	 {
		 Send_Data[19]='1';
	 }
	 else
		 Send_Data[19]='0';
		 
 }
